from qcloudsms_py import SmsSingleSender
from luffyapi.utils.logger import log
from qcloudsms_py.httpclient import HTTPError
from .settings import *


def get_code():
    import random
    s_code = ''
    for i in range(4):
        s_code = s_code + str(random.randint(0, 9))
    return s_code


def send_sms(phone_number, code):
    ssender = SmsSingleSender(appid, appkey)
    params = [code, "3"]  # 当模板没有参数时，`params = []`
    try:
        result = ssender.send_with_param(86, phone_number,
                                         template_id, params, sign=sms_sign, extend="", ext="")
        if result.get('result') == 0:
            return True
        else:
            return False
    except Exception as e:
        log.error(f'手机号：{phone_number}, 短信发送失败，错误为：{str(e)}')
